package net.easyjava.third.aliyun.trans;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.api.AliyunClient;
import com.aliyun.api.DefaultAliyunClient;
import com.aliyun.api.domain.Job;
import com.aliyun.api.domain.JobResult;
import com.aliyun.api.mts.mts20140618.request.QueryJobListRequest;
import com.aliyun.api.mts.mts20140618.request.SubmitJobsRequest;
import com.aliyun.api.mts.mts20140618.response.QueryJobListResponse;
import com.aliyun.api.mts.mts20140618.response.SubmitJobsResponse;
import com.taobao.api.ApiException;
import net.easyjava.third.aliyun.AliyunConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 转码
 * Created by wxnacy on 16/6/1.
 */
public class AliyunTransClient {
    private static Logger logger = LoggerFactory.getLogger(AliyunTransClient.class);
    protected String accessId;
    protected String accessKey;
    /**
     * 构造单例
     */
    private volatile static AliyunTransClient singleton;

    private AliyunTransClient(final String accessId, final String accessKey) {
        this.accessId = accessId;
        this.accessKey = accessKey;
    }

    public static AliyunTransClient getInstance(final String accessId, final String accessKey) {
        if (singleton == null) {
            synchronized (AliyunTransClient.class) {
                if (singleton == null) {
                    singleton = new AliyunTransClient(accessId, accessKey);
                }
            }
        }
        return singleton;
    }


    /**
     * 提交北京转码任务转码
     * @param inBucket
     * @param inKey
     * @param outBucket
     * @param outKey
     * @param pipelinId
     * @param templateId
     * @return
     * @throws ApiException
     */
    public  Job submitBJJobs(String inBucket,String inKey
            ,String outBucket,String outKey,String pipelinId,String templateId) throws ApiException {
        return submitJobs(inBucket, inKey, outBucket, outKey, pipelinId, templateId, AliyunConstants.BUCKET_LOCATION.BJ);
    }

    /**
     * 转码
     * @param inBucket
     * @param inKey
     * @param outBucket
     * @param outKey
     * @param pipelinId
     * @param templateId
     * @param bucketLocation 地区: BJ
     * @return
     * @throws ApiException
     */
    public  Job submitJobs(String inBucket,String inKey
            ,String outBucket,String outKey,String pipelinId,String templateId,
                           AliyunConstants.BUCKET_LOCATION bucketLocation) throws ApiException {
        String location = "";
        String serverUrl = "";
        if(bucketLocation.equals(AliyunConstants.BUCKET_LOCATION.BJ)){
            location = AliyunConstants.LOCATION_BJ;
            serverUrl = AliyunConstants.SERVER_URL_BJ;
        }

        SubmitJobsRequest request = new SubmitJobsRequest();
        JSONObject inputFile = new JSONObject();
        inputFile.put("Bucket", inBucket);
        inputFile.put("Location", location);
        inputFile.put("Object", inKey);
        request.setInput(inputFile.toJSONString());
        request.setOutputBucket(outBucket);
        request.setOutputLocation(location);
        request.setPipelineId(pipelinId);

        JSONArray outputs = new JSONArray();
        JSONObject output = new JSONObject();
        output.put("TemplateId", templateId);
        output.put("OutputObject", outKey);
        outputs.add(output);
        request.setOutputs(outputs.toJSONString());


        AliyunClient aliyunClient = new DefaultAliyunClient(serverUrl, this.accessId, this.accessKey);
        SubmitJobsResponse response = aliyunClient.execute(request);
        if (!response.isSuccess()) {
            throw new ApiException(response.getErrorCode(),response.getMessage());
        }
        List<JobResult> jobResults = response.getJobResultList();
        Job job = null;
        if(jobResults.size()>0){
            job = jobResults.get(0).getJob();
        }
        return job;
    }


    /**
     * 查询转码状态
     * @param jobIds
     * @return
     * @throws ApiException
     */
    public List<Job> queryJobList(String jobIds,AliyunConstants.BUCKET_LOCATION bucketLocation) throws ApiException {
        QueryJobListRequest request = new QueryJobListRequest();
        request.setJobIds(jobIds);
        String serverUrl = "";
        if(bucketLocation.equals(AliyunConstants.BUCKET_LOCATION.BJ)){
            serverUrl = AliyunConstants.SERVER_URL_BJ;
        }

        AliyunClient aliyunClient = new DefaultAliyunClient(serverUrl, this.accessId, this.accessKey);
        QueryJobListResponse response = aliyunClient.execute(request);
        if (!response.isSuccess()) {
            throw new RuntimeException(String.format("queryJobList %s is failed", jobIds));
        }

        List<Job> jobs = response.getJobList();
        return jobs;
    }

}
